package com.example.webbrowser;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.webbrowser.Database.BookMarkManager;
import com.example.webbrowser.Database.WebHistoryDao;
import com.example.webbrowser.Utils.JavascriptInterface;
import com.example.webbrowser.Utils.PageUtils;
import com.example.webbrowser.Utils.RegularUtils;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WebViewActivity extends AppCompatActivity {

    private EditText editText;
    private Button button;
    private boolean isVisible_1 = true;
    private boolean isVisible_2 = false;
    private LinearLayout layout_1, layout_2;
    private Button layout_3;
    private Button web_tab_arrow_left;
    private Button web_tab_arrow_right;
    private Button web_rb_home;
    private Button web_rb_bookmark;
    private Button web_rb_history;
    private Button more;
    private Button cancel;
    private Button web_tab_add_bookmark;

    //增加删除全文按钮
    private ImageView delete_image;
    //收藏书签按钮
    private Button bookmark_btn;
    //进度条
    private ProgressBar progressBar;
    //搜索引擎选择按钮
    private Button engine_btn;
    //所有搜索引擎
    private List<String> engineList = new ArrayList(
            Arrays.asList("https://m.baidu.com/s?word=",
                    "https://www.sogou.com/web?query=",
                    "https://www.so.com/s?q=")
    );
    //搜索引擎对应id
    private int engineSearch = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        Intent intent = getIntent();
        String weburl = intent.getStringExtra("web_url");

        String url;

        if (RegularUtils.regularMatch(weburl)) {
            //说明是url，构造正确的url
            url = RegularUtils.regularGenerate(weburl);
        } else {
            url = engineList.get(engineSearch) + weburl;
        }

        //System.out.println(url);

        editText = (EditText) findViewById(R.id.web_url2);
        button = (Button) findViewById(R.id.run2);
        delete_image = (ImageView) findViewById(R.id.delete2);
        WebView webView = (WebView) findViewById(R.id.wv_webview);

        //书签星星按钮
        bookmark_btn = findViewById(R.id.star);
        //搜索引擎选择按钮
        engine_btn = findViewById(R.id.engine);

        //书签数据库接口
        BookMarkManager bookMarkManager = new BookMarkManager(WebViewActivity.this);
        //历史记录数据库接口
        WebHistoryDao webHistoryDao = new WebHistoryDao(WebViewActivity.this);

        //初始化设置WebView
        webViewSetting(webView);

        //访问网页
        webView.loadUrl(url);
        editText.setText(weburl);
        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        webView.setWebViewClient(new WebViewClient(){

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                 String url = request.getUrl().toString();

                 if("https://www.google.com/".equals(url)) {
                     String str = PageUtils.error();
                     WebResourceResponse webResourceResponse = new WebResourceResponse("text/html", "utf-8", new ByteArrayInputStream(str.getBytes()));
                     return webResourceResponse;
                 } else {
                     return super.shouldInterceptRequest(view, request);
                 }
            }

            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                view.getSettings().setJavaScriptEnabled(true);
                super.onPageStarted(view, url, favicon);
            }

            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public void onPageFinished(WebView view, String url) {
                view.getSettings().setJavaScriptEnabled(true);
                super.onPageFinished(view, url);

                if (webView.getProgress() == 100) {
                    /*************************显示书签**********************************/
                    //如果在数据库中就为true，不在为false
                    boolean isInDatabase = true;
                    String thisUrl = webView.getUrl();  //当前页面的URL
                    String thisTitle = webView.getTitle();   //当前页面的title
                    //查询数据库看该url是否已经在书签中
                    isInDatabase = bookMarkManager.checkURL(thisUrl);
                    Log.d("判断浏览页面是否为书签", thisUrl + "" + thisTitle + ",isInDatabase:" + isInDatabase);
                    //显示星星
                    if (isInDatabase) {
                        bookmark_btn.setBackground(getDrawable(R.drawable.on_star));
                    } else {
                        bookmark_btn.setBackground(getDrawable(R.drawable.no_star));
                    }
                    /*******************************************************************/

                    /************************加入历史记录**********************************/
                    //加入历史记录
                    webHistoryDao.add(thisTitle, thisUrl);
                    Log.d("加入历史记录", thisTitle);
                }
                addImageClickListener(view);//待网页加载完全后设置图片点击的监听方法
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();

                WebView.HitTestResult hit = view.getHitTestResult();
                //hit.getExtra()为null或者hit.getType() == 0都表示即将加载的URL会发生重定向，需要做拦截处理
                if (TextUtils.isEmpty(hit.getExtra()) || hit.getType() == 0) {
                    //通过判断开头协议就可解决大部分重定向问题了，有另外的需求可以在此判断下操作
                    Log.e("重定向", "重定向: " + hit.getType() + " && EXTRA（）" + hit.getExtra() + "------");
                    Log.e("重定向", "GetURL: " + view.getUrl() + "\n" + "getOriginalUrl()" + view.getOriginalUrl());
                    Log.d("重定向", "URL: " + url);
                }

                if (url.startsWith("http://") || url.startsWith("https://")) { //加载的url是http/https协议地址
                    Log.d("得到的URL", url);
                    //view.loadUrl(url);
                    return false; //返回false表示此url默认由系统处理,url未加载完成，会继续往下走

                } else { //加载的url是自定义协议地址
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            }
        }
        );



        progressBar = findViewById(R.id.progressBar);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                editText.setText(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        //WebViewActivity页面搜索框绑定点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(editText.getText())) {
                    String str = editText.getText().toString();
                    String url;

                    if (RegularUtils.regularMatch(str)) {
                        //说明是url，构造正确的url
                        url = RegularUtils.regularGenerate(str);
                    } else {
                        url = engineList.get(engineSearch) + weburl;
                    }
                    editText.clearFocus();
                    webView.loadUrl(url);
                } else {
                    Toast.makeText(WebViewActivity.this, "输入内容为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        /************导航栏新增功能************/
        web_tab_arrow_left = (Button) findViewById(R.id.web_tab_arrow_left);
        web_tab_arrow_right = (Button) findViewById(R.id.web_tab_arrow_right);
        web_rb_home = (Button) findViewById(R.id.web_rb_home);
        web_rb_bookmark = (Button) findViewById(R.id.web_rb_bookmark);
        web_rb_history = (Button) findViewById(R.id.web_rb_history);
        web_tab_add_bookmark = (Button) findViewById(R.id.add_rb_bookmark);
        layout_1 = (LinearLayout) findViewById(R.id.web_rg_tab_bar);
        layout_2 = (LinearLayout) findViewById(R.id.web_rg_tab_bar_active);
        layout_3 = (Button) findViewById(R.id.cancel_button_second);
        //点击触发的图标
        more = (Button) findViewById(R.id.web_tab_bars);
        cancel = (Button) findViewById(R.id.cancel_button_second);
        layout_2.setVisibility(View.GONE);//隐藏布局LinearLayout区域
        layout_3.setVisibility(View.GONE);//隐藏布局Button区域


        //返回键功能
        web_tab_arrow_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    Intent i = new Intent(WebViewActivity.this, MainActivity.class);
                    i.putExtra("fragment_flag", 1);
                    startActivity(i);
                }
            }
        });

        //前进键功能
        web_tab_arrow_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoForward()) {
                    webView.goForward();
                }
            }
        });

        //添加点击跳转事件
        web_rb_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(WebViewActivity.this, MainActivity.class);
                i.putExtra("fragment_flag", 1);
                startActivity(i);
            }
        });

        web_rb_bookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(WebViewActivity.this, MainActivity.class);
                i.putExtra("fragment_flag", 2);
                startActivity(i);
            }
        });

        web_rb_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(WebViewActivity.this, MainActivity.class);
                i.putExtra("fragment_flag", 3);
                startActivity(i);
            }
        });



        //点击隐藏和显示页面布局

        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVisible_1) {
                    isVisible_1 = false;
                    isVisible_2 = true;
                    layout_1.setVisibility(View.GONE);//隐藏布局LinearLayout区域
                    layout_2.setVisibility(View.VISIBLE);//显示布局LinearLayout区域
                    layout_3.setVisibility(View.VISIBLE);//显示布局Button区域
                }
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVisible_2) {
                    isVisible_2 = false;
                    isVisible_1 = true;
                    layout_2.setVisibility(View.GONE);//隐藏布局LinearLayout区域
                    layout_3.setVisibility(View.GONE);//显示布局Button区域
                    layout_1.setVisibility(View.VISIBLE);//隐藏布局LinearLayout区域
                }
            }
        });


        /************搜索框添加删除全文 X 按钮的监听***************/
        //监听textView中是否有内容,决定删除按钮是否显示
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            //长度为0说明是空,隐藏,反之则显示
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    delete_image.setVisibility(View.GONE);
                } else {
                    delete_image.setVisibility(View.VISIBLE);
                }
            }
        });

        /**
         * 根据焦点更改editText搜索框中的文本内容
         * 选中时显示url并全选内容，不选中时显示标题
         */
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //editText.setText(weburl);

                if (hasFocus) {
                    editText.setText(webView.getUrl());
                    editText.selectAll();
                    bookmark_btn.setVisibility(View.GONE);
                    button.setVisibility(View.VISIBLE);
                } else {
                    editText.setText(webView.getTitle());
                    button.setVisibility(View.GONE);
                    bookmark_btn.setVisibility(View.VISIBLE);
                    InputMethodManager imManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                }
            }

        });

        delete_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("");
            }
        });
        /***********************************************/

        /*******************书签功能监听器*******************************/
        View.OnClickListener bookMarkListener= new  View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果要移出书签就改成false，如果加入书签就改为true
                boolean isInDatabase = true;
                String thisUrl = webView.getUrl();  //当前页面的URL
                String thisTitle = webView.getTitle();   //当前页面的title

                //数据库修改
                isInDatabase = bookMarkManager.checkURL(thisUrl);
                Log.d("书签", thisUrl + "" + " " + "isInDatabase" + isInDatabase);

                //显示结果
                if (isInDatabase) {
                    Log.d("浏览——删除书签", thisUrl + "" + thisTitle);
                    bookMarkManager.deleteFavorite(thisUrl);
                    bookmark_btn.setBackground(getDrawable(R.drawable.no_star));
                    //web_tab_add_bookmark.setBackground(getDrawable(R.drawable.no_star));
                    Toast.makeText(WebViewActivity.this, "书签删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d("浏览——增加书签", thisUrl + "" + thisTitle);
                    bookMarkManager.addFavorite(thisTitle, thisUrl);
                    bookmark_btn.setBackground(getDrawable(R.drawable.on_star));
                    Toast.makeText(WebViewActivity.this, "书签加入成功", Toast.LENGTH_SHORT).show();
                }
            }
        };

        /*******************点击书签按钮触发事件*************************/
        web_tab_add_bookmark.setOnClickListener(bookMarkListener);//底部菜单——添加书签
        bookmark_btn.setOnClickListener(bookMarkListener);//右上角书签按钮

        /*************************搜索引擎按钮**************************/
        engine_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建弹出式菜单对象（最低版本11）
                PopupMenu popup = new PopupMenu(v.getContext(), v);//第二个参数是绑定的那个view
                //获取菜单填充器
                MenuInflater inflater = popup.getMenuInflater();
                //填充菜单
                inflater.inflate(R.menu.main, popup.getMenu());
                //绑定菜单项的点击事件
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.baidu:
                                engineSearch = 0;
                                break;
                            case R.id.sogou:
                                engineSearch = 1;
                                break;
                            case R.id.threesixzero:
                                engineSearch = 2;
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                });
                //显示(这一行代码不要忘记了)
                popup.show();
            }
        });

        /********************键盘回车键搜索*********************/
        editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    button.callOnClick();
                    return true;
                }
                return false;
            }
        });
    }

    private void addImageClickListener(WebView view) {
        view.loadUrl("javascript:(function(){"
                +"var objs = document.getElementsByTagName(\"img\"); "
                +"window.imagelistener.setNewArray();"
                +"var Expression=/https:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?/;"
                +"var objExp=new RegExp(Expression);"
                +"var array=new Array();"
                +"var j = 0;"
                + "for(var i=0;i<objs.length;i++)"
                +"{"
                +   "if(objExp.test(objs[i].src))"
                +  "{"
                +    "array[j++] = objs[i];"
                +  "   window.imagelistener.showSource(objs[i].src);  "
                +   "}"
                +"}"
                // "window.imagelistener.showSource(document.getElementsByTagName('html')[0].innerHTML);"
                +"for(var i=0;i<array.length;i++)  "
                +"{"
                + "    array[i].onclick=function()  "
                +"    {  "
                //  +       "var Expression2=/https:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?/;"
                // +       " var objExp2=new RegExp(Expression);"
                +       "if(objExp.test(this.src))"
                +       "{"
                +           "window.imagelistener.openImage(this.src);  "
                +       "}"
                +"    }  " +
                "}" +
                "})()");
    }

    /**
     * 初始化webView的设置
     * @param webView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void webViewSetting(WebView webView) {

        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setDomStorageEnabled(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        // 资源混合模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.addJavascriptInterface(new JavascriptInterface(this), "imagelistener");

    }




    //使浏览页面手机自带的返回键与导航的返回键功能一致
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        WebView webView = (WebView) findViewById(R.id.wv_webview);
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}